package com.bupt.smart.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.R;
import com.bupt.smart.utils.CheckNetwork;
import com.bupt.smart.utils.MD5Util;
import com.bupt.smart.utils.ValidateUserInfo;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.util.Map;

import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressFlower;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int CODE_ING = 1;                  //已发送短信，倒计时
    private static final int CODE_REPEAT = 2;               //重新发送
    private static final int SMSDDK_HANDLER = 3;    //回调
    private AutoCompleteTextView mTelView;
    private EditText mVerificationView;
    private EditText mPasswordView;
    private Button mGetVerifyCode;
    private Button mRegisterButton;

    private ACProgressFlower dialog;

    private EventHandler smsEventHandler = null;
    private final MsgHandler handler = new MsgHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initSMSSDK();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        mTelView = (AutoCompleteTextView) findViewById(R.id.edit_tel);
        mVerificationView = (EditText) findViewById(R.id.edit_verification_code);
        mPasswordView = (EditText) findViewById(R.id.edit_password);
        mGetVerifyCode = (Button) findViewById(R.id.btn_get_verfiy_code);
        mRegisterButton = (Button) findViewById(R.id.btn_register);
        dialog = new ACProgressFlower.Builder(this)
                .direction(ACProgressConstant.DIRECT_CLOCKWISE)
                .themeColor(Color.WHITE)
                .text("注册中")
                .fadeColor(Color.DKGRAY).build();
        mGetVerifyCode.setOnClickListener(this);
        mRegisterButton.setOnClickListener(this);
    }

    private void initSMSSDK() {
        if (smsEventHandler == null) {
            smsEventHandler = new EventHandler() {
                @Override
                public void afterEvent(int event, int result, Object data) {
                    System.out.println("afterEvent");
                    Message msg = new Message();
                    msg.arg1 = event;
                    msg.arg2 = result;
                    msg.obj = data;
                    msg.what = SMSDDK_HANDLER;
                    handler.sendMessage(msg);
                }
            };
        }
        SMSSDK.registerEventHandler(smsEventHandler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_verfiy_code:
                getSmsCode();
                break;
            case R.id.btn_register:
                //注册
                attemptRegister();
                break;
        }
    }

    private void getSmsCode() {
        String tel = mTelView.getText().toString();
        boolean cancel = false;
        // 检查手机号合法性
        if (TextUtils.isEmpty(tel)) {
            mTelView.setError(getString(R.string.error_field_required));
            cancel = true;
        } else if (!ValidateUserInfo.isTelValid(tel)) {
            mTelView.setError(getString(R.string.error_invalid_tel));
            cancel = true;
        }
        if (cancel) {
            //手机号存在错误
            mTelView.requestFocus();
        } else {
            //获取短信验证码
            System.out.println("tel: " + tel);
            SMSSDK.getVerificationCode("86", tel);
        }
    }

    private static class MsgHandler extends Handler {
        private final WeakReference<RegisterActivity> mActivity;

        public MsgHandler(RegisterActivity activity) {
            mActivity = new WeakReference<RegisterActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final RegisterActivity activity = mActivity.get();
            System.out.println("handle msg");
            if (activity != null) {
                switch (msg.what) {
                    case CODE_ING://已发送短信,倒计时
                        break;
                    case CODE_REPEAT://重新发送
                        break;
                    case SMSDDK_HANDLER://回调
                        int event = msg.arg1;
                        int result = msg.arg2;
                        Object data = msg.obj;
                        if (result == SMSSDK.RESULT_COMPLETE) { //回调完成
                            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { //短信验证码验证成功
                                //启动异步任务进行注册操作
                                System.out.println("短信验证成功，开始注册");
                                String phone = activity.mTelView.getText().toString();
                                String password = activity.mPasswordView.getText().toString();
                                try {
                                    password = MD5Util.md5Encode(password);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Call<Map<String, Boolean>> call = APIManager.getUserAPI().register(phone, password);
                                call.enqueue(new retrofit2.Callback<Map<String, Boolean>>() {
                                    @Override
                                    public void onResponse(Call<Map<String, Boolean>> call, Response<Map<String, Boolean>> response) {
                                        activity.dialog.dismiss();
                                        if (response.body().get("result") == true) {
                                            //注册成功
                                            activity.startActivity(new Intent(activity, LoginActivity.class));
                                            activity.finish();
                                        } else {
                                            Toast.makeText(activity, activity.getString(R.string.error), Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<Map<String, Boolean>> call, Throwable t) {
                                        activity.dialog.dismiss();
                                        Toast.makeText(activity, activity.getString(R.string.error), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { //短信验证码已发送
                                System.out.println("1");
                            } else {
                                System.out.println("2");
                                ((Throwable) data).printStackTrace();
                            }
                        } else if (result == SMSSDK.RESULT_ERROR) { //出错
                            try {
                                activity.dialog.dismiss();
                                Throwable throwable = (Throwable) data;
                                throwable.printStackTrace();
                                JSONObject object = new JSONObject(throwable.getMessage());
                                String des = object.optString("detail");//错误描述
                                int status = object.optInt("status");//错误代码
                                if (status > 0 && !TextUtils.isEmpty(des)) {
                                    Toast.makeText(activity, des, Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                }
            }
        }
    }

    private void attemptRegister() {
        // Reset errors.
        mTelView.setError(null);
        mVerificationView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        final String tel = mTelView.getText().toString();
        final String verifyCode = mVerificationView.getText().toString();
        final String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // 检查手机号合法性
        if (TextUtils.isEmpty(tel)) {
            mTelView.setError(getString(R.string.error_field_required));
            focusView = mTelView;
            cancel = true;
        } else if (!ValidateUserInfo.isTelValid(tel)) {
            mTelView.setError(getString(R.string.error_invalid_tel));
            focusView = mTelView;
            cancel = true;
        }

        // 检查短信验证码是否为空
        if (TextUtils.isEmpty(verifyCode)) {
            mVerificationView.setError(getString(R.string.error_field_required));
            focusView = mVerificationView;
            cancel = true;
        }

        // 检查密码合法性
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (!ValidateUserInfo.isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (cancel) {
            //存在错误，取消注册，将屏幕焦点设置为出错的位置
            focusView.requestFocus();
        } else {
            if (!CheckNetwork.isConnected(RegisterActivity.this)) {
                Toast.makeText(RegisterActivity.this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
            } else {
                SMSSDK.submitVerificationCode("86", tel, verifyCode);
                dialog.show();
            }
        }
    }
}
